package com.newsnetwork.exception;

import com.newsnetwork.grace.result.CommonJSONResult;
import com.newsnetwork.grace.result.ResponseStatusEnum;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author DingNing
 * @date 2022/11/4 16:00
 * @Description:统一异常拦截处理,可以针对异常的类型进行捕获，然后返回json信息到前端
 */
@ControllerAdvice
public class GraceExceptionHandler {
    @ExceptionHandler(MyCustomException.class)
    @ResponseBody
    public CommonJSONResult returnMyException(MyCustomException e) {
        e.printStackTrace();
        return CommonJSONResult.exception(e.getResponseStatusEnum());
    }

    /**
     * 处理文件大小异常
     * @param e
     * @return
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseBody
    public CommonJSONResult returnMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
        return CommonJSONResult.errorCustom(ResponseStatusEnum.FILE_MAX_SIZE_ERROR);
    }

    /**
     * 捕获校验异常, 即 BindingResult 中的空数据异常等
     * @param e 捕获的异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public CommonJSONResult returnException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errors = getErrors(bindingResult);
        return CommonJSONResult.errorMap(errors);
    }

    public Map<String, String> getErrors(BindingResult result) {
        Map<String, String> map = new HashMap<>();
        List<FieldError> errorList = result.getFieldErrors();
        for (FieldError error : errorList) {
            String field = error.getField();
            String msg = error.getDefaultMessage();
            map.put(field, msg);
        }

        return map;
    }
}
